﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using EPiServer.Shell.ObjectEditing.EditorDescriptors;

namespace OpenWaves.EPiServer.TagsProperty
{
    [EditorDescriptorRegistration(TargetType = typeof(IEnumerable<string>), UIHint = PropertyTags.UIHint)]
    public class PropertyTagsDescriptor : EditorDescriptor
    {
        public override void ModifyMetadata(global::EPiServer.Shell.ObjectEditing.ExtendedMetadata metadata, IEnumerable<Attribute> attributes)
        {
            var att = attributes.ToArray();

            base.ModifyMetadata(metadata, att);

            var tagsProviderType = att.OfType<TagsProviderAttribute>().Select(a => a.TagsProviderType).FirstOrDefault() ??
                                   typeof (CategoryTagsProvider);

            var tagsProvider = new TagsProviderFactory(tagsProviderType).CreateInstance();

            var enableCustomTags = !att.OfType<DisableCustomTagsAttribute>().Any() && tagsProvider is ITagsStore;

            var currentTagsIds = ((IEnumerable<string>) ((PropertyTags) metadata.Model).Value);
            
            metadata.EditorConfiguration.Add("currentTags", tagsProvider.GetTagsByIDs(currentTagsIds));
            metadata.EditorConfiguration.Add("tagsSource", tagsProvider.GetTags());
            metadata.EditorConfiguration.Add("enableCustomTags", enableCustomTags);
        }

        public PropertyTagsDescriptor()
        {
            this.ClientEditingClass = "ow-epi-tagsProperty.widgets.Tags";
        }
    }
}